package com.example.demo.service.impl;

import com.example.demo.config.JwtConfig;
import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.RegisterRequest;
import com.example.demo.entity.User;
import com.example.demo.entity.UserType;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtConfig jwtConfig;
    private final AuthenticationManager authenticationManager;

    @Override
    public ApiResponse<?> register(RegisterRequest request) {
        // 验证必填字段
        if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
            return ApiResponse.error("用户名不能为空");
        }
        if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
            return ApiResponse.error("密码不能为空");
        }
        if (request.getName() == null || request.getName().trim().isEmpty()) {
            return ApiResponse.error("姓名不能为空");
        }
        if (request.getRole() == null || request.getRole().trim().isEmpty()) {
            return ApiResponse.error("角色不能为空");
        }
        if (request.getCollege() == null || request.getCollege().trim().isEmpty()) {
            return ApiResponse.error("学院不能为空");
        }
        if (request.getPhone() == null || request.getPhone().trim().isEmpty()) {
            return ApiResponse.error("手机号不能为空");
        }

        // 验证角色
        try {
            UserType.valueOf(request.getRole());
        } catch (IllegalArgumentException e) {
            return ApiResponse.error("无效的角色类型，必须是 STUDENT 或 TEACHER");
        }

        // 检查用户名是否已存在
        if (userRepository.existsByUsername(request.getUsername())) {
            return ApiResponse.error("用户名已存在");
        }

        // 根据角色检查学号或工号
        if (request.getRole().equals("STUDENT")) {
            if (request.getStudentId() == null || request.getStudentId().trim().isEmpty()) {
                return ApiResponse.error("学生必须提供学号");
            }
            if (userRepository.existsByStudentId(request.getStudentId())) {
                return ApiResponse.error("学号已被使用");
            }
        } else if (request.getRole().equals("TEACHER")) {
            if (request.getTeacherId() == null || request.getTeacherId().trim().isEmpty()) {
                return ApiResponse.error("教师必须提供工号");
            }
            if (userRepository.existsByTeacherId(request.getTeacherId())) {
                return ApiResponse.error("工号已被使用");
            }
        }

        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setName(request.getName());
        user.setUserType(UserType.valueOf(request.getRole()));
        user.setCollege(request.getCollege());
        user.setPhone(request.getPhone());

        // 根据角色设置相应的ID
        if (user.getUserType() == UserType.STUDENT) {
            user.setStudentId(request.getStudentId());
        } else if (user.getUserType() == UserType.TEACHER) {
            user.setTeacherId(request.getTeacherId());
        }

        userRepository.save(user);

        Map<String, Object> data = new HashMap<>();
        data.put("user", user);
        return ApiResponse.success("注册成功", data);
    }

    @Override
    public ApiResponse<?> login(RegisterRequest request) {
        // 验证必填字段
        if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
            return ApiResponse.error("用户名不能为空");
        }
        if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
            return ApiResponse.error("密码不能为空");
        }

        try {
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );

            User user = (User) authentication.getPrincipal();
            String token = jwtConfig.generateToken(user);

            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            return ApiResponse.success("登录成功", data);
        } catch (Exception e) {
            return ApiResponse.error("用户名或密码错误");
        }
    }
} 